<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterAuthRequest;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use GuzzleHttp\Client;
class ApiController extends Controller
{
    public $loginAfterSignUp = false;
    public $OK = 0;
    public $IllegalAesKey = -41001;
    public $IllegalIv = -41002;
    public $IllegalBuffer = -41003;
    public $DecodeBase64Error = -41004;

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $input = $request->only('openid', 'name', 'avatar', 'gender', 'pid');
        $jwt_token = null;

        if( !isset($input['openid']) || !$input['openid'] ){
            return returnJson(1, "参数缺失");
        }

        if( $input['openid'] == 'undefined' ){
            return returnJson(1, "用户数据获取错误");
        }

//        判断用户是否存在
        $user = User::where('openid', $input['openid'])->first();
        if( !$user ){
            if( !$request->name ){
                return returnJson(1, "用户数据获取错误");
            }
//            注册
            $user = new User();
            $user->openid = $request->openid;
            $user->name = $request->name??"";
            $user->avatar = $request->avatar??"";
            $user->gender = $request->gender??0;
            $user->current_type = 0;
            $user->last_login = date('Y-m-d H:i:s');
            $user->pid = isset($input['pid']) ? intval($input['pid']) : 0;
            $user->save();
        }else{
            DB::table('users')->where('id', $user->id)->update(['last_login'=>date('Y-m-d H:i:s')]);
        }

//        生成token
        if ( !$jwt_token = auth('api')->login($user) ) {
            return returnJson(1, "登录失败，请稍后再试");
        }

        return returnJson(0, '', ['token' => $jwt_token, "user"=>$user]);
    }

    public function getOpenid(Request $request){
        $code = $request->code;
        $APPID = env('APPID')??'wx91cd470f7e9a30e9';
        $APPSECRET = env('APPSECRET')??'52f30b51e08b028aa26017f0c61b8c2c';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$APPID."&secret=".$APPSECRET."&js_code=".$code."&grant_type=authorization_code";
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $url);
        if($response->getStatusCode() == 200){
            $res = json_decode($response->getBody(), true);
            return returnJson(200, '', ['openid' => $res['openid']]);
        }else{
            return returnJson(400, "请求失败");
        }
    }

    //解密小程序获取到的电话
    public function getPhoneNumber(Request $request){
        $code = $request->code;
        $encryptedData = urldecode($request->input('encryptedData'));
        $iv = $request->input('iv');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx91cd470f7e9a30e9&secret=52f30b51e08b028aa26017f0c61b8c2c&js_code=".$code."&grant_type=authorization_code";
        $rs = file_get_contents($url);
        $res = json_decode($rs, true);
        $sessionKey = $res['session_key'];
        $iv = $request->input('iv');
        $phone = $this->decryptData($sessionKey,$encryptedData, $iv);
        if($phone > 0){
            return returnJson('200','',$phone);
        }
        return returnErrorJson($phone);
        /* $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $url);
        if($response->getStatusCode() == 200){
            $res = json_decode($response->getBody(), true);
            $sessionKey = $res['session_key'];
            $encryptedData = $request->input('encryptedData');
            $iv = $request->input('iv');
            $phone = $this->decryptData($sessionKey,$encryptedData, $iv);
            if($phone > 0){
                return returnJson('200','',$phone);
            }
            return returnErrorJson($phone);
        }else{
            return returnJson(400, "请求失败");
        }*/

    }

    public function decryptData( $sessionKey,$encryptedData, $iv )
    {
        if (strlen($sessionKey) != 24) {
            return $this->IllegalAesKey;
        }
        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return $this->IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return $this->IllegalBuffer;
        }
        /*print_r();
        exit();*/
        /*if( $dataObj->watermark->appid != 'wx91cd470f7e9a30e9' )
        {
            return $this->IllegalBuffer;
        }*/
        return $dataObj->phoneNumber;
    }


//    public function getAuthUser(Request $request)
//    {
//        $this->validate($request, [
//            'token' => 'required'
//        ]);
//
//        $user = JWTAuth::authenticate($request->token);
//
//        return response()->json(['user' => $user]);
//    }
}
